package com.atguigu.tingshu.payment.strategy.impl;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.WeChatPayVo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.strategy.PaySubmitStrategy;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderPaySubmitStrategy implements PaySubmitStrategy {

    @Autowired
    private OrderInfoFeignClient orderInfoFeignClient;
    @Autowired
    private RSAAutoCertificateConfig autoCertificateConfig;
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private WxPayV3Config wxPayV3Config;
    @Override
    public WeChatPayVo paySubmit(String paymentType, String orderNo) {
        log.info("orderPaySubmitStrategy......paySubmit执行了");

        // 判断当前订单是否已经过期，如果已经过期了就不需要发送下单请求
        Result<OrderInfo> orderInfoResult = orderInfoFeignClient.getOrderInfo(orderNo);
        OrderInfo orderInfo = orderInfoResult.getData();
        if (SystemConstant.ORDER_STATUS_CANCEL.equals(orderInfo.getOrderStatus())){
            throw new GuiguException(ResultCodeEnum.ORDER_PAYE_TIME_OUT);
        }

        // 保存微信支付的交易信息
        paymentInfoService.savePaymentInfo(orderInfo) ;


        // 使用微信支付平台的SDK请求Jsapi的下单接口，生成预交易订单
        // BigDecimal orderAmount = orderInfo.getOrderAmount();
        WeChatPayVo weChatPayVo = this.requestJsapi(autoCertificateConfig, 1, wxPayV3Config, orderNo, userInfoFeignClient, orderInfo.getOrderTitle());

        // 返回
        return weChatPayVo;
    }

    @Override
    public String getpaymentType() {
        return SystemConstant.PAYMENT_TYPE_ORDER;
    }
}
